// component/authorization/authorization.js
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    recommendShow: false, // 控制推荐关注组件显隐
    user_show: false,
    phone_show: false,
    shows: false,
    code: '',
    user_time: '',
    phone_time: '',
    avatarUrl: '',
    avatarUrls: 'https://lechuang-video-test-1259368925.cos.ap-guangzhou.myqcloud.com/tiezhi/tubiao/imge_nomal_wchat.png',
    nickname: '',
    login_show: false,
    choose_index: 1,
    explain_show: false,
    set_show: false,
    input_phone: '',
    phonecode_show: false,
    phone_code: '',
    num: 30,
    title: '发送验证码',
    time: '',
    off: false,
    conceal: false,
    showPrivacy: false
  },
  observers: {
    show: function (show) {
      this.show_demo()
    }
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () {
      const that = this;
      app.watch(function () { //监听token变化，弹出授权页面
        that.show_demo()
      })
      that.show_demo()
    },
    hide: function () { },
    resize: function () { },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    choose_img(e) {
      let index = e.currentTarget.dataset.index
      this.setData({
        choose_index: index
      })
    },
    show_explain() {
      this.setData({
        explain_show: true,
        shows: false,
        user_show: false,
        phone_show: false
      })
    },
    back_show_explain() {
      this.setData({
        explain_show: false
      })
      this.show_demo()
    },
    //使用其他头像和昵称
    show_set_other() {
      this.setData({
        set_show: true,
        shows: false,
        user_show: false,
        phone_show: false
      })
    },
    close_show_set() {
      this.setData({
        set_show: false,
      })
      this.show_demo()
    },
    // 推荐组件响应事件
    recommendShowChange(e) {
      console.log('推荐', e.detail)
      this.setData({
        recommendShow: false
      })
    },
    show_phonecode() {
      this.setData({
        phonecode_show: true
      })
    },
    show_demo() {
      const that = this;
      let nickname = app.dlc.gain('nickname') ? app.dlc.gain('nickname') : '';
      let token = app.dlc.gain('token') ? app.dlc.gain('token') : ''
      wx.getPrivacySetting({
        success: res => {
          // console.log(res) 
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            this.setData({
              showPrivacy: true
            })
          }
        },
        fail: () => { },
        complete: () => { }
      })
      if (!token && !that.data.login_show) {
        that.setData({
          shows: true,
          user_show: true,
          phone_show: false
        })
      } else if (!token && that.data.login_show) {
        that.setData({
          shows: true,
          user_show: false,
          phone_show: true
        })
      } else {
        that.setData({
          shows: false,
          user_show: false,
          phone_show: false
        })
      }
    },
    onClose() {
      this.setData({
        shows: false
      })
    },
    onChooseAvatar(e) {
      console.log(e)
      const that = this;
      that.setData({
        avatarUrl: e.detail.avatarUrl
      })
      console.log(that.data.avatarUrl)
      wx.setStorageSync('avatar', e.detail.avatarUrl);
    },
    close_demo_show() {
      this.setData({
        shows: false,
        user_show: false,
        phone_show: false
      })
    },
    get_nickname(e) {
      this.setData({
        nickname: e.detail.value
      })
    },
    login_user() { //code登陆
      const that = this;
      if (this.data.conceal) {
        that.logins()
      } else {
        app.toast('请先阅读用户隐私协议')
      }
    },
    logins() {
      const that = this;
      app.loading()
      wx.login({
        success(result) {
          if (result.code) {
            app.wxRequest('/api/Users/checkLogin', {
              code: result.code
            }, function (res) {
              that.setData({
                login_show: true
              })
              if (res.code == 200) {
                if (res.data.info) {
                  wx.setStorageSync('token', res.data.AccessToken)
                  wx.setStorageSync('user_info', res.data.info)
                  app.globalData.token = res.data.AccessToken
                }
                that.show_demo()
                that.login_sucess()
                that.get_theme()
              } else {
                app.toast(res.message)
              }
              wx.hideLoading()
            })
          } else {
            app.toast('code获取失败')
          }
        }
      })
    },
    get_code() {
      const that = this;
      that.setData({
        shows: false
      })
      wx.login({
        success(result) {
          if (result.code) {
            console.log(result.code)
            that.setData({
              code: result.code
            })
          } else {
            app.toast('code获取失败')
          }
        }
      })
    },
    // 输入手机号码
    getphone(e) {
      const that = this;
      let value = e.detail.value;
      if (app.dlc.checkPhone(value)) {
        this.setData({
          input_phone: value
        })
        wx.login({
          success(result) {
            if (result.code) {
              that.setData({
                code: result.code
              })
            } else {
              app.toast('code获取失败')
            }
          }
        })
      }
    },
    //输入手机验证码
    get_phone_code(e) {
      this.setData({
        phone_code: e.detail.value
      })
    },
    //请求验证码
    code_request() {
      const that = this;
      if (app.dlc.checkPhone(that.data.input_phone)) {
        app.loading()
        app.wxRequests('/auth/sms/sendcode', {
          phone: that.data.input_phone
        }, function (res) {
          if (res.code == 200) {
            that.get_codes()
          } else {
            app.toast(res.message)
          }
        }, 'get')
      } else {
        app.toast('手机号码不正确')
      }
    },
    //验证码倒计时
    get_codes() {
      const that = this;
      let num = that.data.num;
      let times;
      that.setData({
        off: true
      })
      times = setInterval(() => {
        if (num > 0) {
          num--;
          that.setData({
            time: times,
            num: num
          })
        } else {
          clearInterval(that.data.time)
          num = 30
          that.setData({
            off: false,
            num: num
          })
        }
      }, 1000);
    },
    //下一步
    login_input_phone() {
      const that = this;
      if (!that.data.input_phone) {
        app.toast('您输入手机号码不正确')
      } else if (!that.data.phone_code) {
        app.toast('请输入您的手机验证码')
      } else {
        app.loading()
        app.wxRequests('/auth/social/login', {
          sex: app.dlc.gain('gender') == 0 ? 3 : app.dlc.gain('gender'),
          phone: that.data.input_phone,
          code: that.data.code,
          phonecode: that.data.phone_code,
          bindUsername: app.dlc.gain('nickname') ? app.dlc.gain('nickname') : '',
          nickname: app.dlc.gain('nickname') ? app.dlc.gain('nickname') : '',
          avatar: app.dlc.gain('avatar') ? app.dlc.gain('avatar') : '',
          source: app.dlc.wx_appid == 2 ? 'applet_community' : 'wechat_bangfu'
        }, function (res) {
          if (res.code == 200) {
            wx.setStorageSync('token', res.data.AccessToken)
            app.globalData.token = res.data.AccessToken
            that.show_demo()
            that.login_sucess()
            that.get_theme()
          } else {
            app.toast(res.message)
          }
        })
      }
    },
    getPhoneNumber(e) { //绑定手机
      const that = this;
      if (that.data.shows) {
        return false
      }
      if (e.detail.errMsg == 'getPhoneNumber:ok') {
        let iv = e.detail.iv; e
        let encryptedData = e.detail.encryptedData;
        let code = '';
        app.loading()
        app.wxRequest('/api/Users/wxLogin', {
          encryptedData: encryptedData,
          iv: iv,
          code: that.data.code
        }, function (res) {
          if (res.code == 200) {
            wx.setStorageSync('token', res.data.AccessToken)
            app.globalData.token = res.data.AccessToken
            wx.setStorageSync('user_info', res.data.info)
            that.show_demo()
            that.login_sucess()
            that.get_theme()
          } else {
            app.toast(res.message)
          }
        })
      }
    },
    bind_lag_lng() { //上传当前坐标
      const that = this;
      if (!that.data.lat) {
        return false
      }
      let lat = that.data.lat;
      let lng = that.data.lng;
      app.wxRequest('/app/personalHome/updatePersonal', {
        latitude: app.dlc.transformtxbd(lat, lng).lat,
        longitude: app.dlc.transformtxbd(lat, lng).lng
      }, function (res) {
        if (res.code == 200) {

        } else {
          app.toast(res.message)
        }
      })
    },
    go_conceal() {
      wx.navigateTo({
        url: '/personal_center/pages/userAgreement/index?id=3',
      })
    },
    choose_conceal() {
      const that = this;
      let latitude = app.dlc.gain('latitude')
      let longitude = app.dlc.gain('longitude')
      // if (!longitude || !latitude) {
      //   wx.getLocation({
      //     type: 'wgs84',
      //     success(res) {
      //       console.log('授权获取地理位置经纬度', res)
      //       const latitude = res.latitude
      //       const longitude = res.longitude
      //       // 本地存储经纬度,避免频繁调用
      //       wx.setStorageSync('latitude', res.latitude)
      //       wx.setStorageSync('longitude', res.longitude)
      //       that.setData({
      //         lat: latitude,
      //         lng: longitude
      //       })
      //     }
      //   })
      // }
      this.setData({
        conceal: !this.data.conceal
      })
    },
    handleAgreePrivacyAuthorization(e) {

    },
    login_sucess() {
      this.triggerEvent('sucess')
    },
    get_theme() {
      const that = this;
      if (app.dlc.gain('user_info')) {
        app.wxRequest('/api/Users/getHostById', {
          id: app.dlc.gain('user_info').host
        }, function (res) {
          if (res.code == 200) {
            if (res.data) {
              wx.setStorageSync('theme_color', res.data.theme)
              wx.setStorageSync('brand_title', res.data.name)
              wx.setStorageSync('brand', res.data.host)
              that.login_sucess()
            }
          }
        })
      }
    }
  }
})